package com.alinesno.cloud.operation.cmdb.common.jobs;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import com.alinesno.cloud.operation.cmdb.common.constants.OrderStatusEnum;
import com.alinesno.cloud.operation.cmdb.common.constants.ParamsEnum;
import com.alinesno.cloud.operation.cmdb.entity.OrdersEntity;
import com.alinesno.cloud.operation.cmdb.entity.UserEntity;
import com.alinesno.cloud.operation.cmdb.repository.OrderRepository;
import com.alinesno.cloud.operation.cmdb.repository.UserRepository;
import com.alinesno.cloud.operation.cmdb.service.OrderRecordService;
import com.alinesno.cloud.operation.cmdb.service.ParamsService;
import com.alinesno.cloud.operation.cmdb.third.wechat.WechatService;

/**
 * 定时任务,判断订单是否被销售员接
 * 
 * @author LuoAnDong
 * @since 2018年8月11日 下午12:37:58
 */
//@Component
public class OrderSalatimeJob {

	private static final Logger logger = LoggerFactory.getLogger(OrderSalatimeJob.class);

	@Autowired
	private WechatService wechatService;

	@Autowired
	private OrderRepository orderRepository;
	
	@Autowired
	private UserRepository userRepository ;
	
	@Autowired
	private OrderRecordService orderRecordService ; //订单记录服务 
	
	@Autowired
	private ParamsService paramsService ; 

	// 每分钟做一次订单表扫描，并查询出未接的订单，并判断时间是否超过时间
	@Scheduled(cron = "0 0/1 * * * ?")
	public void timerToNow() {

		// 查询所有未接的订单
		List<OrdersEntity> list = orderRepository.findBySendStatusAndSalaIdIsNotNull(OrderStatusEnum.ORDER_PENDING.getCode());

		if (list != null) {
			
			logger.debug("判断是否未有指定销售员任务,未接订单量:{}", list.size());
			
			for (OrdersEntity e : list) {
				int outTime = paramsService.findParamByNameToInt(ParamsEnum.ORDER_SALA_OUTTIME.getCode() , e.getMasterCode())  ; 
				
				// 判断是否超时
				long startTime = e.getAddTime().getTime();
				long now = System.currentTimeMillis();
				long time = (now - startTime) / 1000;

				String logDetail = String.format("销售员:%s 订单:%s 未有接单,间隔时间:%s ，超时时间：%s",e.getSalaId() , e.getOrderId() , time , outTime) ; 
				logger.debug(logDetail) ; 

				if (time > outTime) { // 设置订单超时
					orderRecordService.saveRecord(e.getOrderId(), OrderStatusEnum.ORDER_PENDING.code , e.getUserId() , logDetail); //保存订单记录
					UserEntity user = userRepository.findById(e.getSalaId()).get() ; // 超时订单给用户发送提醒
					
					if(user != null) {
						wechatService.sendTaskMessageToSchool(e.getOrderId(), user.getId() , e.getMasterCode()) ; 
					}else {
						wechatService.sendTaskMessageToSchool(e.getOrderId(), null , e.getMasterCode()) ; 
					}
					
				} 
			}
		}
	}

}
